package com.example.controller;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

@RestController
@RequestMapping("/wechat")
public class SelfWeCharController {
    private static final String TOKEN = "wechat";

    @GetMapping              // 完整路径 = /wechat
    public ResponseEntity<String> verify(
            @RequestParam String signature,
            @RequestParam String timestamp,
            @RequestParam String nonce,
            @RequestParam String echostr) {

        System.out.println("verify");
        // 1. 纯内存计算，无 DB、无日志落盘
        String[] arr = {TOKEN, timestamp, nonce};
        Arrays.sort(arr);
        String sha1 = DigestUtils.sha1Hex(String.join("", arr));

        // 2. 5 秒内必返回
        return sha1.equals(signature)
                ? ResponseEntity.ok().contentType(MediaType.TEXT_PLAIN).body(echostr)
                : ResponseEntity.ok("fail");
    }

    @GetMapping("/test")
    public String test(){
        return "success";
    }
}